package com.donleo.stmg.common;

import com.donleo.stmg.common.api.CommonResult;
import com.donleo.stmg.utils.CommonPath;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author liangd
 * date 2020-11-24 18:32
 * code 图片上传接口
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    @PostMapping("/img")
    public CommonResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("上传失败");
        }
        //文件名称
        String fileName = file.getOriginalFilename();
        //文件位置
        String filePath = CommonPath.SAVE_PATH.getValue() + CommonPath.IMG_PATH.getValue();
        //全路径
        File dest = new File(filePath + fileName);
        //数据库保存地址
        String imgPath = CommonPath.IMG_PATH.getValue() + fileName;
        try {
            file.transferTo(dest);
            return CommonResult.success(imgPath);
        } catch (IOException e) {
            return CommonResult.failed("上传失败");
        }
    }
}
